<?php
namespace app\admin\controller\wechat\material;

use app\admin\controller\Controller;
use app\admin\model\Material as MaterialModel;
use app\admin\model\Wechat as WechatModel;
use think\facade\View;

/**
 * 视频素材
 */
class Video extends Controller
{
    /**
     * 列表
     */
    public function index()
    {
        $model = new MaterialModel;
        $list = $model->getList(30);
        $wechat = WechatModel::detail();
        return View::fetch('index', compact('list','wechat'));
    }

    /**
     * 删除
     */
    public function delete($id)
    {
        $model = MaterialModel::get($id);
        if (!$model->remove()) {
            $error = $model->getError() ?: '删除失败';
            return $this->renderError($error);
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            if(!$wechat = WechatModel::detail()){
                return $this->renderError('还未绑定公众号');
            }
            if($wechat['status']['value'] == 0){
                return $this->renderError('还未绑定公众号');
            }
            $model = new MaterialModel;
            // 新增记录
            $file = request()->file('file');
            $file_path = \think\facade\Filesystem::disk('public')->putFile('wechat',$file);
            // 新增记录
    		if($model->add($this->postData('data'),$file_path)){
    			return $this->renderSuccess('添加成功', url('wechat.material.video/index'));
    		}
            $error = $model->getError() ?: '添加失败';
            return $this->renderError($error);
        }
        return redirect(url('wechat.material.video/index')); 
    }

    /**
     * 编辑
     */
    public function edit($id)
    {
        $model = MaterialModel::get($id);
        if ($this->request->isGet()) {
            if($model){
               return $this->renderSuccess('', '', compact('model')); 
            }
            return $this->renderError('获取失败');
        }
        // 更新记录
		if(!$wechat = WechatModel::detail()){
            return $this->renderError('还未绑定公众号');
        }
        if($wechat['status']['value'] == 0){
            return $this->renderError('还未绑定公众号');
        }
        // 更新记录
        if ($model->edit($this->postData('data'))) {
            return $this->renderSuccess('更新成功', url('wechat.material.video/index'));
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }

}
